<?php
	/**
	 * Output buffer.
	 * @author IMP
	 */
	
	class OutputBuffer {
		private $buffer = array();
		
		public function __construct($capture = true, $autopublish = false){
			if($capture) ob_start(array($this, 'write'));
			else ob_start();
			
			if($autopublish){
				Environment::addShutdownCallback(array($this, 'publish'), false);
			}
		}
		
		public function close(){
			ob_end_clean();
		}
		
		public function write($data){
			$this->buffer[] = $data;
		}
		
		public function writeln($data){
			$this->buffer[] = $data . PHP_EOL;
		}
		
		public function writebr($data){
			$this->buffer[] = $data . '<br />';
		}
		
		public function publish(){
			echo $this->getContents();
			$this->clear();
		}
		
		public function clear(){
			$this->buffer = array();
		}
		
		public function getContents(){
			return implode('', $this->buffer);
		}
		
		public function __toString(){
			return $this->getContents();
		}
		
		private static $stdout = true;
		
		public static function enableOutput(){
			if(!self::$stdout){
				ob_end_clean();
				self::$stdout = true;
			}
		}
		
		public static function disableOutput(){
			if(self::$stdout){
				ob_start();
				self::$stdout = false;
			}
		}
		
		public static function clearOutput(){
			ob_end_clean();
		}
	}
?>